package com.trinh.utils.crypto.utils;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @Author: TrinhRae
 * @Package: com.trinh.utils.crypto
 * @Project: generaltools
 * @Date: 2025/6/20 10:28
 */
public class KeyUtil {

    private static final String CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final SecureRandom RANDOM = new SecureRandom();

    /**
     * 随机生成utf8的密钥
     *
     * @param length 密钥长度
     * @return
     */
    public static String randomKey(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(CHARSET.charAt(RANDOM.nextInt(CHARSET.length())));
        }
        return sb.toString();
    }

    /**
     * 生成 AES Base64位的随机密钥（支持 128, 192, 256）
     *
     * @param keySize 密钥位数（128, 192, 256）
     * @return Base64 编码的密钥
     */
    public static String generateAesKey(int keySize, String encodeFormat) throws Exception {
        if (keySize != 128 && keySize != 192 && keySize != 256) {
            throw new IllegalArgumentException("AES 密钥长度只能是 128/192/256 位");
        }

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(keySize);
        SecretKey secretKey = keyGen.generateKey();
        byte[] encoded = secretKey.getEncoded();

        switch (encodeFormat.toLowerCase()) {
            case "base64":
                return Base64.getEncoder().encodeToString(encoded);
            case "hex":
                return bytesToHex(encoded);
            case "raw":
                return new String(encoded);
            default:
                throw new IllegalArgumentException("不支持的编码格式: " + encodeFormat);
        }
    }

    /**
     * 字节转Hex
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     * 生成非对称加密密钥对（默认 2048 位）
     */
    public static KeyPair generateKeyPair(int keySize) throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(keySize);
        return keyPairGen.generateKeyPair();
    }

    /**
     * 获取 Base64 编码的公钥字符串
     */
    public static String getBase64PublicKey(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
    }

    /**
     * 获取 Base64 编码的私钥字符串
     */
    public static String getBase64PrivateKey(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
    }

    public static void main(String[] args) throws Exception {
        KeyPair keyPair = generateKeyPair(1024);
        System.out.println("公钥：" + getBase64PublicKey(keyPair));
        System.out.println("密钥：" + getBase64PrivateKey(keyPair));

    }
}
